package com.wisdom.weld.service.impl;

import com.wisdom.weld.pojo.ColumnAttribute;
import com.wisdom.weld.pojo.TableAttribute;
import com.wisdom.weld.service.DatabaseDataService;
import com.wisdom.weld.util.DBUtils;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DatabaseDataServiceImpl implements DatabaseDataService {

    @Override
    public List<TableAttribute> getTableAttributes() {
        Connection connection = DBUtils.getConnection();
        List<TableAttribute> tableAttributes = new ArrayList<>();
        try{
            String catalog = connection.getCatalog();
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet tables = metaData.getTables(catalog, DBUtils.getUserName(), null, new String[]{"TABLE"});
            while(tables.next()){
                TableAttribute tableAttribute = new TableAttribute();
                String tableName = tables.getString(3);// TABLE_NAME
                String comment = tables.getString(5);// REMARKS
                tableAttribute.setTableName(tableName);
                tableAttribute.setComment(comment);
                tableAttributes.add(tableAttribute);
                ResultSet columns = metaData.getColumns(catalog, DBUtils.getUserName(), tableName, null);
                List<ColumnAttribute> columnAttributes = new ArrayList<>();
                ResultSet primaryKeys = metaData.getPrimaryKeys(catalog, null, tableName);
                String primaryKeyName = null;
                while(primaryKeys.next()){
                    primaryKeyName = primaryKeys.getString("COLUMN_NAME");
                }
                while(columns.next()){
                    ColumnAttribute columnAttribute = new ColumnAttribute();
                    String columnName = columns.getString("COLUMN_NAME");
                    String remarks = columns.getString("REMARKS");
                    String typeName = columns.getString("TYPE_NAME");
                    columnAttribute.setColumnName(columnName);
                    columnAttribute.setComment(remarks);
                    columnAttribute.setTypeName(typeName);
                    columnAttributes.add(columnAttribute);
                    if (columnName.equals(primaryKeyName)) {
                        columnAttribute.setIsPrimaryKey(Boolean.TRUE);
                    }
                }

                tableAttribute.setColumnAttributes(columnAttributes);
            }
        } catch(SQLException e){
            throw new RuntimeException("获取数据库信息异常");
        }
        return tableAttributes;
    }
}
